package com.pmcc.utils;

import com.aliyuncs.*;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.push.model.v20160801.PushMessageToAndroidRequest;
import com.aliyuncs.push.model.v20160801.PushMessageToAndroidResponse;
import com.aliyuncs.push.model.v20160801.PushNoticeToAndroidRequest;
import com.aliyuncs.push.model.v20160801.PushNoticeToAndroidResponse;
import com.pmcc.core.entity.SmsRecord;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 阿里云短消息服务
 * @author yaonan
 * @Date 2018年11月20日
 */
public class SmsSendUtil {

    public static final String DEFAULT_CONNECT_TIMEOUT = "10000";//默认的链接超时时间
    public static final String DEFAULT_READ_TIMEOUT = "10000";//默认的读取超时时间
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    static  final  String accessKeyId=SystemPropertyUtil.getProperty("accessKeyId");
    static  final  String accessKeySecret=SystemPropertyUtil.getProperty("accessKeySecret");
    static  final  String signName="煜东科技";

    public static IAcsClient acsClient=null;

    public static  IAcsClient getAcsClient() throws ClientException {
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        acsClient = new DefaultAcsClient(profile);
        return  acsClient;
    }
    public static SendSmsResponse sendSms(String telephone,String code,String str) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", DEFAULT_CONNECT_TIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", DEFAULT_READ_TIMEOUT);


        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(telephone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(code);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        request.setTemplateParam(str);
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");

        //hint 此处可能会抛出异常，注意catch
        getAcsClient();
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }

    /**
     * 模版1
     * @param telephone 手机号，支持多手机号，字符串以逗号分割
     * @param message 【煜东科技】$factory上报了一个有关 $questionType 的问题。
     * @return
     */
    public static SmsRecord sendSmsCode1(String telephone,String message){
        String code=SystemPropertyUtil.getProperty("templateCode1");
        SendSmsResponse response = null;
        try {
            response = sendSms(telephone,code,message);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        SmsRecord smsRecord=new SmsRecord(message,code,telephone,response.getCode(),new Date());
        return  smsRecord;
    }

    /**
     * 模版2
     * @param telephone 手机号，支持多手机号，字符串以逗号分割
     * @param message 煜东科技】$name 您好，您有$factory 的一个问题需要解决。
     * @return
     */
    public static SmsRecord sendSmsCode2(String telephone,String message){
        String code=SystemPropertyUtil.getProperty("templateCode2");
        SendSmsResponse response = null;
        try {
            response = sendSms(telephone,code,message);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        SmsRecord smsRecord=new SmsRecord(message,code,telephone,response.getCode(),new Date());
        return  smsRecord;
    }
    /**
     * 模版2
     * @param telephone
     * @param message 验证码${code}，您正在进行身份验证，打死不要告诉别人哦！。
     * @return
     */
    public static SmsRecord sendSmsCode3(String telephone,String message){
        String code=SystemPropertyUtil.getProperty("templateCode3");
        SendSmsResponse response = null;
        try {
            response = sendSms(telephone,code,message);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        SmsRecord smsRecord=new SmsRecord(message,code,telephone,response.getCode(),new Date());
        return  smsRecord;
    }

    /**
     * 基础的推送信息到安卓
     * @param androidRequest
     * @param appKey
     * @param target
     * @param targetValue
     * @param title
     * @param body
     * @throws ClientException
     */
    public  static void basePushMessageToAndroid( PushMessageToAndroidRequest androidRequest, Long appKey, String target, String targetValue, String title, String body)throws ClientException {
        androidRequest.setProtocol(ProtocolType.HTTP);
        //内容较大的请求，使用POST请求
        androidRequest.setMethod(MethodType.POST);
        androidRequest.setAppKey(appKey);
        androidRequest.setTarget(target);
        androidRequest.setTargetValue(targetValue);
        androidRequest.setTitle(title);
        androidRequest.setBody(body);
        getAcsClient();
    }

    /**
     * 基础的推送通知到安卓
     * @param androidRequest
     * @param appKey
     * @param target
     * @param targetValue
     * @param title
     * @param body
     * @throws ClientException
     */
    public  static void basePushNoticeToAndroid( PushNoticeToAndroidRequest androidRequest, Long appKey, String target, String targetValue, String title, String body)throws ClientException {

        androidRequest.setProtocol(ProtocolType.HTTP);
        //内容较大的请求，使用POST请求
        androidRequest.setMethod(MethodType.POST);
        androidRequest.setAppKey(appKey);
        androidRequest.setTarget(target);
        androidRequest.setTargetValue(targetValue);
        androidRequest.setTitle(title);
        androidRequest.setBody(body);
        getAcsClient();
    }

    /**
     * 封装的推送信息到安卓
     * @param appKey
     * @param target
     * @param targetValue
     * @param title
     * @param body
     * @return
     * @throws ClientException
     */
    public  static PushMessageToAndroidResponse pushMessageToAndroid(Long appKey,String target,String targetValue,String title,String body) throws ClientException {
        PushMessageToAndroidRequest androidRequest = new PushMessageToAndroidRequest();

        basePushMessageToAndroid(androidRequest,appKey,target,targetValue,title,body);
        PushMessageToAndroidResponse pushMessageToAndroidResponse = acsClient.getAcsResponse(androidRequest);
        return pushMessageToAndroidResponse;
    }

    /**
     *封装的推送通知到安卓
     */
    public static PushNoticeToAndroidResponse pushNoticeToAndroid(Long appKey,String target,String targetValue,String title,String body,String ext) throws Exception {

        PushNoticeToAndroidRequest androidRequest = new PushNoticeToAndroidRequest();

        basePushNoticeToAndroid(androidRequest,appKey,target,targetValue,title,body);
        //ext格式"{\"k1\":\"v1\"}"
        androidRequest.setExtParameters(ext);

        PushNoticeToAndroidResponse pushNoticeToAndroidResponse = acsClient.getAcsResponse(androidRequest);
        return pushNoticeToAndroidResponse;


    }
    /**
     * 查询短信详情
     * @param bizId 业务id
     * @param telephone 手机号
     * @return
     * @throws ClientException
     */
    public static QuerySendDetailsResponse querySendDetails(String bizId,String telephone) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", DEFAULT_CONNECT_TIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", DEFAULT_READ_TIMEOUT);

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(telephone);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    /**
     * 推送信息给易生产
     * @param target
     * @param targetValue
     * @param title
     * @param body
     */
    public  static  void pushMessageToProductAndroid(String target,String targetValue,String title,String body){
        Long appkey=Long.parseLong(SystemPropertyUtil.getProperty("appKey1"));
        try {
            pushMessageToAndroid(appkey,target,targetValue,title,body);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送信息给维捷云
     * @param target
     * @param targetValue
     * @param title
     * @param body
     */
    public  static  void pushMessageToFactoryAndroid(String target,String targetValue,String title,String body){
        Long appkey=Long.parseLong(SystemPropertyUtil.getProperty("appKey2"));
        try {
            pushMessageToAndroid(appkey,target,targetValue,title,body);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送通知给易生产
     * @param target
     * @param targetValue
     * @param title
     * @param body
     */
    public  static  void pushNoticeToProductAndroid(String target,String targetValue,String title,String body,String ext){
        Long appkey=Long.parseLong(SystemPropertyUtil.getProperty("appKey1"));
        try {
            pushNoticeToAndroid(appkey,target,targetValue,title,body,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 有参的推送通知给易生产
     * @param target
     * @param targetValue
     * @param title
     * @param body
     */
    public  static  void pushNoticeToProductAndroidExt(String target,String targetValue,String title,String body,String ext){
        Long appkey=Long.parseLong(SystemPropertyUtil.getProperty("appKey1"));
        try {
            pushNoticeToAndroid(appkey,target,targetValue,title,body,ext);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 无参的推送通知给维捷云
     * @param target
     * @param targetValue
     * @param title
     * @param body
     */
    public  static  void pushNoticeToFactoryAndroid(String target,String targetValue,String title,String body){
        Long appkey=Long.parseLong(SystemPropertyUtil.getProperty("appKey2"));
        try {
            pushNoticeToAndroid(appkey,target,targetValue,title,body,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送给维捷云含有额外参数
     * @param target
     * @param targetValue
     * @param title
     * @param body
     * @param ext
     */
    public  static  void pushNoticeToFactoryAndroidExt(String target,String targetValue,String title,String body,String ext){
        Long appkey=Long.parseLong(SystemPropertyUtil.getProperty("appKey2"));
        try {
            pushNoticeToAndroid(appkey,target,targetValue,title,body,ext);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws ClientException {

        Long appkey=Long.parseLong(SystemPropertyUtil.getProperty("appKey1"));
        String target="DEVICE";
        String targetValue="cfd8b3d9fba9488c8933f62b97458d34";
        String title="ceshi";
        String body="123123";
       //推送信息
       pushMessageToAndroid(appkey,target,targetValue,title,body);
       //推送通知
      // pushNoticeToAndroid(appkey,target,targetValue,title,body);
//        String telephone="15737151037";
//        String code=SystemPropertyUtil.getProperty("templateCode1");
//        String str="{\"factory\":\"金春无纺布金春7线\", \"questionType\":\"机械故障\"}";
//        //发短信
//        try {
//            SendSmsResponse response = sendSms(telephone,code,str);
//            System.out.println("短信接口返回的数据----------------");
//            System.out.println("Code=" + response.getCode());
//            System.out.println("Message=" + response.getMessage());
//            System.out.println("RequestId=" + response.getRequestId());
//            System.out.println("BizId=" + response.getBizId());
//            Thread.sleep(3000L);
//
//            //查明细
//            if(response.getCode() != null && response.getCode().equals("OK")) {
//                QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId(),telephone);
//                System.out.println("短信明细查询接口返回数据----------------");
//                System.out.println("Code=" + querySendDetailsResponse.getCode());
//                System.out.println("Message=" + querySendDetailsResponse.getMessage());
//                int i = 0;
//                for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
//                {
//                    System.out.println("SmsSendDetailDTO["+i+"]:");
//                    System.out.println("Content=" + smsSendDetailDTO.getContent());
//                    System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
//                    System.out.println("OutId=" + smsSendDetailDTO.getOutId());
//                    System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
//                    System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
//                    System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
//                    System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
//                    System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
//                }
//                System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
//                System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
//            }
//        } catch (ClientException | InterruptedException e) {
//            e.printStackTrace();
//        }


    }
}
